package com.jy.novel.utils;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Random;

public class Captcha {
	private ByteArrayInputStream image;//验证码图像
	private String captchaStr;//验证码字符串
	public Captcha(){
		init();//初始化，生成验证码和验证码图片
	}
	//取得Captcha实例
	public static Captcha Instance(){
		return new Captcha();
	}
	public ByteArrayInputStream getImage() {
		return image;
	}
	//取得验证码图片
	public void setImage(ByteArrayInputStream image) {
		this.image = image;
	}
	//获取验证码字符串
	public String getCaptchaStr() {
		return captchaStr;
	}
	public void setCaptchaStr(String captchaStr) {
		this.captchaStr = captchaStr;
	}
	private void init(){
		int width=80,height=25;
		String [] codeStrs = new String[]{
				"0","1","2","3","4","5","6","7","8","9",
				"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
				"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
		};
		//在内存中创建图像
		BufferedImage buffferImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		//获取图像上下文
		Graphics g = buffferImage.getGraphics();
		//生成随机类
		Random random = new Random(); 
		//设定背景色
		g.setColor(Color.white);
		g.fillRect(0, 0, width, height);
		//设定字体
		g.setFont(new Font("Times New Roman",Font.PLAIN,18));
		// 随机产生干扰线，使图象中的验证码不易被其它程序探测到 
		for (int i=0;i<random.nextInt(100)+150;i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
			g.drawLine(x, y, x, y);
		}
		// 取随机产生的认证码(4位)
		String randStr = "";
		for(int i=0;i<4;i++){
			String str = codeStrs[random.nextInt(codeStrs.length)];
			randStr += str;
			//将验证码显示到图像中
			 g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
			 g.drawString(str,13*i+6,18);
		}
		//图象生效       
		g.dispose();
		ByteArrayInputStream input=null;
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		try {
			ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
			ImageIO.write(buffferImage, "JPEG", imageOut);
			imageOut.close();
			input = new ByteArrayInputStream(output.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
		}
		captchaStr = randStr;
		image = input;
	}
}
